package cn.highedu.security;

import cn.highedu.dao.UserDao;
import cn.highedu.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * UserDetailsService 会自动配置到 认证管理器
 */
@Component // @Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private UserDao userDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        logger.debug("登录用户名：{}", username);
        User user = userDao.findUserByName(username);
        if (user == null){
            throw new UsernameNotFoundException("没有找到用户信息");
        }
        UserDetailsImpl userDetails = new UserDetailsImpl(user);
        // 如果是明文密码就进行加密处理
        if (user.getPassword().startsWith("{noop}")) {
            String password = user.getPassword().substring(6);
            user.setPassword(passwordEncoder.encode(password));
            userDao.updateUser(user);
        }
        logger.debug("登录用户: {}", user);
        return userDetails;
    }
}
